﻿using SyncUdp.Interface;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SyncUdp
{
    public interface IResourceManager : ISingleton
    {
        public T Load<T>(string path) where T : UnityEngine.Object;

        public void LoadAsync<T>(string path, Action<T> onLoaded) where T : UnityEngine.Object;

        public void CloseGame();
    }

    /// <summary>
    /// 资源加载管理器
    /// </summary>
    public class ResourceManager : AbstractSingleton, IResourceManager
    {
        ResourceManagerHelper _helper;

        protected override void OnInit()
        {
            // 实例化一个资源加载的物体
            var go = new GameObject("ResourceManagerHelper");
            _helper = go.AddComponent<ResourceManagerHelper>();
            var architecture = Transform.FindObjectOfType<ArchitectureController>();
            _helper.transform.SetParent(architecture.transform);
        }

        /// <summary>
        /// 同步加载
        /// </summary>
        public T Load<T>(string path) where T : UnityEngine.Object
        {
            return Resources.Load<T>(path);
        }

        /// <summary>
        /// 异步加载
        /// </summary>
        public void LoadAsync<T>(string path, Action<T> onLoaded) where T : UnityEngine.Object
        {
            _helper.StartCoroutine(LoadResAsync(path, onLoaded));
        }

        IEnumerator LoadResAsync<T>(string path, Action<T> onLoaded) where T : UnityEngine.Object
        {
            var op = Resources.LoadAsync(path);
            yield return op;
            onLoaded?.Invoke(op.asset as T);
        }

        public void CloseGame()
        {
            Resources.UnloadUnusedAssets();
        }

        #region 辅助类
        /// <summary>
        /// 辅助资源加载的类
        /// </summary>
        class ResourceManagerHelper : MonoBehaviour
        {
            
        }
        #endregion
    }
}
